package com.allo2o.common.utils;

import com.allo2o.shared.util.StringUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * <ul>
 * 短信平台
 * </ul>
 * Created by lubingbing on 16-5-7.
 */
public class SMSPlatform {

    /**
     * <ul>
     * 发送短信
     * </ul>
     *
     * @param content 文本 example: 注册验证码为123456
     * @param mobile  mobile number
     * @throws Exception
     */
    public static String sendSMS(String content, String mobile, String type) throws Exception {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httppost = new HttpPost("http://114.55.8.158:9090/sendmobilemsg/sendmsg");
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("CONTENT", content));
        params.add(new BasicNameValuePair("MOBILE", mobile));
        params.add(new BasicNameValuePair("sign", mobile));
        // 如果传递了type类型,则发送语音短信
        if (!StringUtils.isBlank(type)) {
            params.add(new BasicNameValuePair("type", type));
        }
        UrlEncodedFormEntity uefEntity;
        uefEntity = new UrlEncodedFormEntity(params, "UTF-8");
        httppost.setEntity(uefEntity);
        System.out.println("executing request " + httppost.getURI());
        CloseableHttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        if (null != entity) {
            return EntityUtils.toString(entity, "UTF-8");
        }
        response.close();
        httpclient.close();
        return null;
    }
}
